# -*- coding: utf-8 -*-

from usuarios.models import Usuario

# XXX FIXME Workaround para os testes.
def is_test(request):
    if request.META.get('SERVER_NAME') == 'testserver' and request.META.get('REMOTE_ADDR') == '127.0.0.1':
        return True
    return False

class LazyUser(object):
    def __get__(self, request, obj_type=None):
        if not hasattr(request, '_cache_user'):
            if 'auth' in request.session:
                user_id = request.session['auth']
                try:
                    # TODO usar select_related para reduzir queries (trazer permissoes)
                    request._cached_user = Usuario.objects.select_related('grupo').get(id=user_id)
                except:
                    request._cached_user = None
                    del request.session['auth']
            else:
                request._cached_user = None

        return request._cached_user

class AuthenticationMiddleware(object):
    def process_request(self, request):
        # XXX FIXME Workaround para os testes.
        if is_test(request):
            user, created = Usuario.objects.get_or_create(nome='Test User', usuario='testuser', senha='testuser', superusuario=True, ativo=True)
            request.session['auth'] = user.id
        request.__class__.user = LazyUser()
        request.__class__.is_logged = 'auth' in request.session
        return None

